import React, { PureComponent } from 'react';
import PropTypes from 'prop-types';
import { routerRedux } from 'dva/router';
import { connect } from 'dva';
import {
  Table,
  Icon,
  Divider,
  Form,
  Select,
  DatePicker,
  Input,
  Card,
  Tag,
  Avatar,
  Checkbox,
  Rate,
  Progress,
  Button,
  Dropdown,
  Row,
  Col,
  Modal,
  Spin,
  Collapse,
  message,
  List,
  Radio,
  Tabs,
} from 'antd';

import PageHeaderLayout from '../../../layouts/PageHeaderLayout';
import FooterToolbar from 'components/FooterToolbar';
import querystring from 'querystring';
import ApplyOrderDisplayer from '../../../components/Falcon/ApplyOrderDisplayer';
import CustomerList from '../../../components/Falcon/CustomerList';
import ImageUploader from '../../../components/Falcon/Attachment/ImageUploader';
import CustomerChecker from '../../../components/Falcon/Customer/CustomerChecker';
import AssetChecker from '../../../components/Falcon/Asset/AssetChecker';
import RepaymentAbilityChecker from '../../../components/Falcon/RepaymentAbility/RepaymentAbilityChecker';
import DescriptionList from '../../../components/DescriptionList';

import styles from './style.less';

const Panel = Collapse.Panel;
const FormItem = Form.Item;
const RadioGroup = Radio.Group;
const { TextArea } = Input;
const Option = Select.Option;
const { Description } = DescriptionList;
const { TabPane } = Tabs;
const ButtonGroup = Button.Group;

const formItemLayout = {
  labelCol: {
    span: 5,
  },
  wrapperCol: {
    span: 19,
  },
};

@connect(({ risk, apply }) => ({
  risk,
  apply,
}))
@Form.create()
export default class CheckDetail extends PureComponent {
  state = {
    width: '100%',
    projectId: '',
    taskId: '',
    modalVisible: false,
    approvalResult: false,
  };

  componentDidMount() {
    const { dispatch, location } = this.props;
    const params = querystring.parse(location.search.slice(1));
    this.setState({
      projectId: params.id,
      taskId: params.taskId,
    });
    dispatch({
      type: 'risk/getBusinessDetails',
      payload: {
        projectId: params.id,
      },
    });

    window.addEventListener('resize', this.resizeFooterToolbar);
  }
  componentWillUnmount() {
    window.removeEventListener('resize', this.resizeFooterToolbar);
  }

  resizeFooterToolbar = () => {
    const sider = document.querySelectorAll('.ant-layout-sider')[0];
    const width = `calc(100% - ${sider.style.width})`;
    if (this.state.width !== width) {
      this.setState({ width });
    }
  };

  renderCustomerFooter(creditVerify, customer, index) {
    const { getFieldDecorator } = this.props.form;
    const formItemLayoutOfFooter = {
      labelCol: {
        span: 3,
      },
      wrapperCol: {
        span: 21,
      },
    };
    // console.log("creditVerify", creditVerify)
    return (
      <FormItem label="审批意见" {...formItemLayoutOfFooter}>
        {getFieldDecorator(`creditVerify[${index}]`, {
          initialValue: creditVerify[index].creditVerify,
        })(
          <Radio.Group>
            <Radio value={1}>
              <span style={{ color: 'green' }}>
                一致<Icon type="check" />
              </span>
            </Radio>
            <Radio value={0}>
              <span style={{ color: 'red' }}>
                不同<Icon type="close" />
              </span>
            </Radio>
          </Radio.Group>
        )}
      </FormItem>
    );
  }

  progressColumns = [
    {
      title: '指标',
      dataIndex: 'name',
      key: 'name',
      width: 150,
    },
    {
      title: '初审',
      dataIndex: 'state',
      key: 'state',
      render: (text, item) => {
        return (
          <div>
            {/* {console.log("item.childrens", item)} */}
            {item.childrens.map(child => {
              if ((child.key == '1-1' || child.key == '4-1') && child.state) {
                return (
                  child.state != -1 &&
                  child.state.map(item => {
                    switch (item.relation) {
                      case 1:
                        return this.handleCustomeVerify('', item.verify, '主申请人身份认证');
                      case 2:
                        return this.handleCustomeVerify('', item.verify, '共同还款人身份认证');
                      case 3:
                        return this.handleCustomeVerify('', item.verify, '担保人身份认证');
                    }
                  })
                );
              } else {
                return this.handleCustomeVerify(child.key, child.state, child.name);
              }
            })}
          </div>
        );
      },
    },
  ];

  handleCustomeVerify = (key, state, name) => {
    switch (state) {
      case 1:
        return (
          <Tag color="green">
            {name} <Icon type="check" style={{ color: 'green' }} />
          </Tag>
        );
      case 0:
        return (
          <Tag color="red">
            {name} <Icon type="close" style={{ color: 'red' }} />
          </Tag>
        );
      case -1:
        return (
          <div>
            {key == '1-2' ? null : (
              <Tag>
                {name} <Icon type="minus" style={{ color: 'gray' }} />
              </Tag>
            )}
          </div>
        );
    }
  };

  handleClickShow = () => {
    this.setState({
      modalVisible: true,
    });
  };

  handleModalCancel = () => {
    this.setState({
      modalVisible: false,
    });
  };

  haandleApprovalSubmit = () => {
    this.setState({
      approvalResult: true,
    });
  };

  handleApprovalReviewSubmit = () => {
    const { dispatch } = this.props;
    const { validateFieldsAndScroll } = this.props.form;
    let result = null;
    validateFieldsAndScroll((error, values) => {
      if (!error) {
        if (values.resultCode) {
          if (values.resultCode == '1') {
            result = '通过';
          }
          if (values.resultCode == '2') {
            result = '驳回';
          }
          if (values.resultCode == '3') {
            result = '拒绝';
          }
          dispatch({
            type: 'risk/commitDoApproval',
            payload: {
              projectId: this.state.projectId,
              taskId: this.state.taskId,
              ...values,
              result: result,
              type: 1,
            },
            callback: () => {
              const { risk: { riskResult } } = this.props;
              if (riskResult.code == 200) {
                this.setState({
                  approvalResult: false,
                });
                message.success('提交成功');
                dispatch(routerRedux.push('/risk/checkList'));
              } else {
                message.error(riskResult.message);
              }
            },
          });
        } else {
          message.warning('请选择审核结果');
        }
      }
    });
  };

  handleApprovalModalCancel = () => {
    this.setState({
      approvalResult: false,
    });
  };

  handleReviewSubmit = () => {
    this.setState({
      modalVisible: false,
    });
  };

  haandleCreditVerifySubmit = () => {
    const { dispatch } = this.props;
    const { validateFieldsAndScroll } = this.props.form;
    const { risk } = this.props;
    const { riskBusinessDetails } = risk;

    validateFieldsAndScroll((error, values) => {
      if (!error) {
        // console.log("validateFieldsAndScroll", riskBusinessDetails.creditVerify)
        let creditVerify = [];
        if (values.creditVerify.length > 0) {
          for (let i = 0; i < values.creditVerify.length; i++) {
            creditVerify.push({
              customerId: riskBusinessDetails.creditVerify[i].id,
              verify: values.creditVerify[i],
              relation: riskBusinessDetails.creditVerify[i].relation,
            });
          }
        }
        dispatch({
          type: 'risk/commitinCreditVerify',
          payload: {
            projectId: this.state.projectId,
            creditVerify,
          },
          callback: () => {
            const { risk: { riskResult } } = this.props;
            if (riskResult.code == 200) {
              message.success('提交成功');
              dispatch({
                type: 'risk/getBusinessDetails',
                payload: {
                  projectId: this.state.projectId,
                },
              });
              // dispatch(routerRedux.push('/risk/reviewList'));
            } else {
              message.error(riskResult.message);
            }
          },
        });
      }
    });
  };

  render() {
    const { risk: { riskBusinessDetails, riskLoading, riskHomeVisitLoading } } = this.props;
    const { getFieldDecorator } = this.props.form;

    const action = (
      <div style={{ flex: '1' }}>
        <ButtonGroup>
          <Button onClick={this.handleClickShow}>审批结果</Button>
          {/* <Button onClick={this.handleProgress}>审批记录</Button> */}
        </ButtonGroup>
      </div>
    );

    return (
      <PageHeaderLayout
        title="业务审核详情"
        className={styles.channelDetailsContainer}
        action={action}
      >
        {/* {JSON.stringify(riskBusinessDetails)} */}
        {riskLoading ? (
          <div className={styles.spinContainer}>
            <Spin size="large" />
          </div>
        ) : (
          riskBusinessDetails &&
          riskBusinessDetails.business && (
            <div>
              <Card title="业务摘要" className={styles.preCheckFormCard}>
                {/* <ApplyOrderDisplayer /> */}
                {riskBusinessDetails.business && (
                  <DescriptionList className={styles.headerList} size="small" col="3">
                    <Description term="客户名称">
                      {riskBusinessDetails.business.custName}
                    </Description>
                    <Description term="证件号">{riskBusinessDetails.business.idcard}</Description>
                    <Description term="担保公司">
                      {riskBusinessDetails.business.orgName}
                    </Description>
                    <Description term="经销商">
                      {riskBusinessDetails.business.dealerName}
                    </Description>
                    <Description term="所购车型">
                      {riskBusinessDetails.business.carType}
                    </Description>
                    <Description term="车价">
                      {riskBusinessDetails.business.dealerPrice}
                    </Description>
                    <Description term="首付款">
                      {riskBusinessDetails.business.firstPayment}
                    </Description>
                    <Description term="分期金额">
                      {riskBusinessDetails.business.loanAmt}
                    </Description>
                    <Description term="分期数">
                      {riskBusinessDetails.business.loanDuration == null
                        ? 0
                        : riskBusinessDetails.business.loanDuration}
                    </Description>
                    <Description term="手续费率">
                      {riskBusinessDetails.business.intrest}%
                    </Description>
                    <Description term="手续费">{riskBusinessDetails.business.fee}</Description>
                  </DescriptionList>
                )}
              </Card>

              <Card title="详情审核" style={{ marginTop: '16px' }}>
                <Tabs tabPosition="left">
                  <TabPane
                    tab={
                      <span>
                        客户核实
                        {riskBusinessDetails.verifyStatus &&
                        riskBusinessDetails.verifyStatus.split('')[0] == '1' ? (
                          <Icon type="check" style={{ color: 'green' }} />
                        ) : (
                          <span style={{ marginRight: '22px' }} />
                        )}
                      </span>
                    }
                    key="1"
                  >
                    {riskBusinessDetails.customerVerify && (
                      <CustomerChecker
                        hideThirdVerify={true}
                        checkDetailsValue={true}
                        projectId={this.state.projectId}
                      />
                    )}
                  </TabPane>
                  <TabPane
                    tab={
                      <span>
                        资产核实
                        {riskBusinessDetails.verifyStatus &&
                        riskBusinessDetails.verifyStatus.split('')[1] == '1' ? (
                          <Icon type="check" style={{ color: 'green' }} />
                        ) : (
                          <span style={{ marginRight: '22px' }} />
                        )}
                      </span>
                    }
                    key="2"
                  >
                    {riskBusinessDetails.assetsVerify && (
                      <AssetChecker checkDetailsValue={true} projectId={this.state.projectId} />
                    )}
                  </TabPane>
                  <TabPane
                    tab={
                      <span>
                        收入核实
                        {riskBusinessDetails.verifyStatus &&
                        riskBusinessDetails.verifyStatus.split('')[2] == '1' ? (
                          <Icon type="check" style={{ color: 'green' }} />
                        ) : (
                          <span style={{ marginRight: '22px' }} />
                        )}
                      </span>
                    }
                    key="4"
                  >
                    {riskBusinessDetails.incomeVerify && (
                      <RepaymentAbilityChecker
                        checkDetailsValue={true}
                        projectId={this.state.projectId}
                      />
                    )}
                  </TabPane>
                  <TabPane
                    tab={
                      <span>
                        资信核实{' '}
                        {riskBusinessDetails.verifyStatus &&
                        riskBusinessDetails.verifyStatus.split('')[3] == '1' ? (
                          <Icon type="check" style={{ color: 'green' }} />
                        ) : (
                          <span style={{ marginRight: '22px' }} />
                        )}
                      </span>
                    }
                    key="3"
                  >
                    {riskBusinessDetails.creditVerify && (
                      <CustomerList
                        hideDocuments={true}
                        checkDetailsValue={true}
                        projectId={this.state.projectId}
                        customerFooter={(customer, index) => {
                          return this.renderCustomerFooter(
                            riskBusinessDetails.creditVerify,
                            customer,
                            index
                          );
                        }}
                      />
                    )}
                    <Form>
                      <FormItem
                        style={{ marginLeft: '30px', marginTop: '30px' }}
                        wrapperCol={{ span: 21, offset: 3 }}
                        label=""
                      >
                        <Button type="primary" onClick={this.haandleCreditVerifySubmit}>
                          保存
                        </Button>
                      </FormItem>
                    </Form>
                  </TabPane>
                </Tabs>
              </Card>
            </div>
          )
        )}
        <FooterToolbar style={{ width: this.state.width }}>
          <Button type="primary" onClick={this.haandleApprovalSubmit}>
            提交
          </Button>
        </FooterToolbar>

        <Modal
          title={'审批结果'}
          visible={this.state.modalVisible}
          onOk={this.handleReviewSubmit}
          onCancel={this.handleModalCancel}
          footer={null}
        >
          {
            // JSON.stringify(riskBusinessDetails && riskBusinessDetails.verifyNote)
          }
          <Table
            columns={this.progressColumns}
            dataSource={riskBusinessDetails && riskBusinessDetails.verifyNote}
            size="small"
            rowKey="key"
            bordered={false}
            pagination={false}
            style={{ marginBottom: 20 }}
          />
        </Modal>
        <Modal
          title={'审批结果'}
          visible={this.state.approvalResult}
          onOk={this.handleApprovalReviewSubmit}
          onCancel={this.handleApprovalModalCancel}
          confirmLoading={riskHomeVisitLoading}
        >
          <Row>
            <Col span={24}>
              <FormItem label="审核结果" {...formItemLayout}>
                {getFieldDecorator('resultCode', {})(
                  <Radio.Group>
                    <Radio value="1">通过</Radio>
                    <Radio value="2">驳回</Radio>
                    {/* <Radio value="3">否决</Radio> */}
                  </Radio.Group>
                )}
              </FormItem>
              <FormItem label="审核意见" {...formItemLayout}>
                {getFieldDecorator('content', {})(<TextArea rows={4} />)}
              </FormItem>
            </Col>
          </Row>
        </Modal>
      </PageHeaderLayout>
    );
  }
}
